package com.yzt.loginmodule.login;

import android.annotation.SuppressLint;
import android.app.ActivityOptions;
import android.content.Intent;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.yzt.loginmodule.regist.RegisterUploadAvatarActivity;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.arouter.RouterAccount;
import com.yzt.zhuju.arouter.RouterMain;
import com.yzt.zhuju.base.BaseActivity;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.user.LoginBean;
import com.yzt.zhuju.network.entity.user.UserLoginInfo;
import com.yzt.loginmodule.R;
import com.yzt.loginmodule.widget.VerifyEditText;
import com.yzt.p_base.utils.ToastUtil;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

/**
 * author : bob
 * date   : 2022/12/1
 * desc   : 验证码登录
 */
@SuppressLint({"CheckResult", "SetTextI18n"})
@Route(path = RouterAccount.ACTIVITY_VERIFY_CODE)
public class VerifyCodeActivity extends BaseActivity {

    @Autowired
    String mobile;

    @Autowired
    String zone;

    /**
     * 1:登录/注册；2第三方登录绑定手机号 3:换绑手机号
     */
    @Autowired
    int type;

    @Autowired
    String accessToken;

    @Autowired
    String openId;

    private TextView tvCountDownTime;

    private Disposable countDownDisposable;

    @Override
    public int getLayoutId() {
        return R.layout.activity_verify_code;
    }

    @Override
    public void installViews() {
        setFullScreen(true, R.color.transparent);
        findViewById(R.id.iv_close_left).setOnClickListener(this);
        TextView tvMobileNumber = findViewById(R.id.tv_mobile_number);
        tvMobileNumber.setText(mobile);

        tvCountDownTime = findViewById(R.id.tv_countdonw_time);
        tvCountDownTime.setOnClickListener(this);
        tvCountDownTime.setEnabled(false);
        VerifyEditText editSecurityCode = findViewById(R.id.edit_security_code);
        editSecurityCode.addInputCompleteListener(new VerifyEditText.InputCompleteListener() {
            @Override
            public void complete(@NonNull String content) {
                if (type == 1) {
                    goOtherRegister(content);
                }
                if (type == 3) {
                    phoneUpdate(content);
                }
            }
        });
        stateCountDown();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownDisposable != null) {
            if (!countDownDisposable.isDisposed()) {
                countDownDisposable.dispose();
            }
            countDownDisposable = null;
        }
        stopTimer();
    }

    private void stateCountDown() {
        startCountCode();
    }

    private Disposable disposable;

    /**
     * 执行倒计时
     */
    @SuppressLint("StringFormatInvalid")
    public void startCountCode() {
        final long count = 60;
        disposable = Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(count + 1)
                .doOnSubscribe(disposable ->
                        tvCountDownTime.setEnabled(false)
                )
                .subscribe(aLong -> runOnUiThread(() -> {
                    if (count - aLong == 1) {
                        tvCountDownTime.setSelected(true);
                        tvCountDownTime.setEnabled(true);
                    } else {
                        tvCountDownTime.setSelected(false);
                        tvCountDownTime.setText("重新获取（" + (count - aLong) + "s）");
                    }
                }), throwable -> {

                }, () -> {

                });
    }

    /**
     * 停止定时执行
     */
    protected void stopTimer() {
        if (null != disposable) {
            disposable.dispose();
            disposable = null;
        }
    }

    /**
     * 新用户注册
     */
    private void goOtherRegister(String code) {

        BizLayer.getInstance().getAccountModule().otherLogin(code,
                mobile,
                new AresSubscriber<LoginBean>() {
                    @Override
                    protected void onSuccess(LoginBean userLoginInfo) {
                        UserLoginInfo info = new UserLoginInfo();
                        info.setAuthed(userLoginInfo.isRegistered());
                        info.setToken(userLoginInfo.getToken());
                        UserLoginInfo.LoginInfo loginInfo = new UserLoginInfo.LoginInfo();
                        loginInfo.setUid(userLoginInfo.getUserId());
                        info.setUserInfo(loginInfo);
                        RXingUtils.saveLoginAccount(info);
                        if (userLoginInfo.isRegistered()) {
                            RouterMain.MainActivity();
                        } else {
                            Intent intent = new Intent(mActivity, RegisterUploadAvatarActivity.class);
                            startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(mActivity).toBundle());
                        }
                        setResult(RESULT_OK);
                        finish();
                    }

                    @Override
                    protected void onFinallyEnd() {
                        super.onFinallyEnd();
                        closeProgress();
                    }
                });
    }

    /**
     * 修改手机号
     */
    private void phoneUpdate(String code) {
        BizLayer.getInstance().getAccountModule().accountPhoneUpdate(mobile, code,
                new AresSubscriber<Object>() {
                    @Override
                    protected void onSuccess(Object userLoginInfo) {
                        ToastUtil.showMessage("手机号修改成功！");
                        finish();
                    }

                    @Override
                    protected void onFinallyEnd() {
                        super.onFinallyEnd();
                        closeProgress();
                    }
                });
    }

    @Override
    protected void onClick(int clickId) {
        super.onClick(clickId);
        if (clickId == R.id.iv_close_left) {
            finish();
        }
        if (clickId == R.id.tv_countdonw_time) {
            getMsgCode();
        }
    }

    /**
     * 获取验证码
     */
    private void getMsgCode() {
        if (mobile.length() != 11) {
            ToastUtil.showMessage("请输入完整的手机号");
            return;
        }
        if (type == 1) {
            BizLayer.getInstance().getAccountModule().getLoginCode(mobile, new AresSubscriber() {
                @Override
                protected void onSuccess(Object o) {
                    stateCountDown();
                }

                @Override
                protected void onError(int code, String info) {
                    super.onError(code, info);
                    ToastUtil.showMessage(info);
                }

                @Override
                protected void onFinallyEnd() {
                    super.onFinallyEnd();
                    closeProgress();
                }
            });
        } else if (type == 3) {
            BizLayer.getInstance().getAccountModule().getAccountPhoneUpdateCode(mobile, new AresSubscriber() {
                @Override
                protected void onSuccess(Object o) {
                    stateCountDown();
                }

                @Override
                protected void onError(int code, String info) {
                    super.onError(code, info);
                    ToastUtil.showMessage(info);
                }

                @Override
                protected void onFinallyEnd() {
                    super.onFinallyEnd();
                    closeProgress();
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            mActivity.finish();
        }
    }
}